package 面试;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

// 请求参数类
class ReqParam {
    private String id;
    private String data;

    public ReqParam(String id, String data) {
        this.id = id;
        this.data = data;
    }

    public String getId() {
        return id;
    }

    public String getData() {
        return data;
    }
}

// 响应结果类
class RespResult {
    private String reqId;
    private String result;
    @SuppressWarnings("unused")
    private long timestamp;

    public RespResult(String reqId, String result) {
        this.reqId = reqId;
        this.result = result;
        this.timestamp = System.currentTimeMillis();
    }

    @Override
    public String toString() {
        return "RespResult{reqId='" + reqId + "', result='" + result + "'}";
    }
}

// 模拟外部服务调用
class ExternalService {
    // 模拟调用外部接口，返回处理结果
    public static RespResult call(ReqParam param) {
        // 模拟网络延迟
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return new RespResult(param.getId(), "处理完成: " + param.getData());
    }
}

// 业务处理类
public class UnsynchronizedResultCollection {

    // 处理请求列表的方法
    public List<RespResult> processRequests(List<ReqParam> params) throws InterruptedException {
        // 共享的结果列表 - 未进行同步控制
        List<RespResult> results = new ArrayList<>();

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 为每个请求创建一个任务
        for (ReqParam param : params) {
            executor.submit(() -> {
                // 调用外部服务获取结果
                RespResult result = ExternalService.call(param);
                // 直接添加到共享列表 - 线程不安全操作
                results.add(result);
                System.out.printf("线程 %s 已添加结果: %s%n",
                        Thread.currentThread().getName(), result);
            });
        }

        // 关闭线程池并等待所有任务完成
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.MINUTES);

        return results;
    }

    public static void main(String[] args) throws InterruptedException {
        // 创建10个请求参数
        List<ReqParam> params = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            params.add(new ReqParam("req-" + i, "数据-" + i));
        }

        // 处理请求
        UnsynchronizedResultCollection processor = new UnsynchronizedResultCollection();
        List<RespResult> results = processor.processRequests(params);

        // 输出结果
        System.out.println("\n最终收集的结果数量: " + results.size());
        System.out.println("预期结果数量: 10");
        for (RespResult result : results) {
            System.out.println(result);
        }
    }
}
